package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Text;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;



public class FragmentA extends Fragment implements View.OnClickListener {
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Toast curToast;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curDepartNo,curDepart,CPUID;
    Button btn_find,btn_Query;
    ImageButton btn_editBarcode;
    ListView detailListView;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_PO,txt_Color,txt_FlowerModel,txt_Size,txt_ReadyScan,txt_OwenScan,txt_Number,txt_TargetNum,txt_TodaySewNum;
    EditText edt_barcode;
    JSONArray detailJSON;
    String language="";


    public static final int msgFocusBarcode = 1001;
    public static final int msgError = 1002;
    public static final int msgScanOver = 1003;
    public static final int msgDetailOver = 1004;
    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public FragmentA() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerA(new MainActivity.OnTransParamsListenerA() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {

                            Log.d("FragmentA","LoginParam------------------>1");
                            System.out.println(mParams);
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            CPUID=mParams.get("CPUID").toString();
                            language= mParams.get("language").toString();
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.sendMessage(msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }



    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case msgFocusBarcode:
                        //设置焦点
                        System.out.println("FragmentA 设置焦点-------------------------------1.Start");
                        setEditBarcodeFocus();
                        System.out.println("FragmentA 设置焦点-------------------------------1.End");
                        break;
                    case msgScanOver:
                        fillFormtext();
                        break;
                    case msgDetailOver:
                        //显示预排单;
                        final DetailListAdapter detailListAdapter = new DetailListAdapter(getActivity());
                        detailListView.setAdapter(detailListAdapter);
                        break;
                    case msgError:
                        Bundle bundle=msg.getData();
                        curToast.setText(bundle.getString("HintInfo"));
                        curToast.show();
                        break;
                    default:
                        break;
                }
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_a, container, false);
        initView(root);
        System.out.println("fragment_a_onCreateView");
        return root;
    }


    private void initView(View view) {
        detailListView=(ListView) view.findViewById(R.id.detailListView);
        btn_find=(Button)view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_Query=(Button)view.findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        btn_editBarcode=(ImageButton)view.findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        btn_editBarcode.setFocusable(false);
        btn_editBarcode.setFocusableInTouchMode(false);
        //界面Edit;
        edt_barcode=(EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        hideIM(v);
                        if (edt_barcode.getText().length()==0) {
                            curToast.setText(getString(R.string.PleaseInputBarcode));
                            curToast.show();
                        }
                        //执行查询;
                        searchBarcodeData(edt_barcode.getText().toString(),txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString());
                    }

                }
                return false;
            }
        });
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        txt_HintInfo=(TextView)view.findViewById(R.id.txt_HintInfo);
        txt_OrderNo=(TextView)view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=(TextView)view.findViewById(R.id.txt_StyleNo);
        txt_PO=(TextView)view.findViewById(R.id.txt_PO);
        txt_Color=(TextView)view.findViewById(R.id.txt_Color);
        txt_FlowerModel=(TextView)view.findViewById(R.id.txt_FlowerModel);
        txt_Size=(TextView)view.findViewById(R.id.txt_Size);
        txt_ReadyScan=(TextView)view.findViewById(R.id.txt_ReadyScan);
        txt_OwenScan=(TextView)view.findViewById(R.id.txt_OwenScan);
        txt_Number=(TextView)view.findViewById(R.id.txt_Number);
        txt_TargetNum=(TextView)view.findViewById(R.id.txt_TargetNum);
        txt_TodaySewNum=(TextView)view.findViewById(R.id.txt_TodaySewNum);

        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);
    }



    //刷新缸布列表;
    private void searchBarcodeData(String BarcodeParam,String OrderNoParam,String StyleNoParam)
    {
        try {
            detailJSON=new JSONArray("[]");
            //清除界面显示内容;
            clearFormText();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_AScanBarcode @Barcode='" + BarcodeParam + "',@OrderNo='" + OrderNoParam + "',@StyleNo='" + StyleNoParam
                + "',@OPERTYPE='SCANBARCODE',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"',@LNG='"+language+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //清除界面显示内容
    private void clearFormText(){
        /*

        */
    }
    //填充界面显示内容;
    private void fillFormtext(){
        if (detailJSON.length()>0)
        {
            try {
                if (detailJSON.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(detailJSON.getJSONObject(0).getString("HintInfo"));
                if (detailJSON.getJSONObject(0).has("OrderNo")==true) txt_OrderNo.setText(detailJSON.getJSONObject(0).getString("OrderNo"));
                if (detailJSON.getJSONObject(0).has("StyleNo")==true) txt_StyleNo.setText(detailJSON.getJSONObject(0).getString("StyleNo"));
                if (detailJSON.getJSONObject(0).has("PO")==true) txt_PO.setText(detailJSON.getJSONObject(0).getString("PO"));
                if (detailJSON.getJSONObject(0).has("Color")==true) txt_Color.setText(detailJSON.getJSONObject(0).getString("Color"));
                if (detailJSON.getJSONObject(0).has("FlowerModel")==true) txt_FlowerModel.setText(detailJSON.getJSONObject(0).getString("FlowerModel"));
                if (detailJSON.getJSONObject(0).has("Size")==true) txt_Size.setText(detailJSON.getJSONObject(0).getString("Size"));
                if (detailJSON.getJSONObject(0).has("ReadyScan")==true) txt_ReadyScan.setText(detailJSON.getJSONObject(0).getString("ReadyScan"));
                if (detailJSON.getJSONObject(0).has("OwenScan")==true) txt_OwenScan.setText(detailJSON.getJSONObject(0).getString("OwenScan"));
                if (detailJSON.getJSONObject(0).has("Number")==true) txt_Number.setText(detailJSON.getJSONObject(0).getString("Number"));
                if (detailJSON.getJSONObject(0).has("TargetNum")==true) txt_TargetNum.setText(detailJSON.getJSONObject(0).getString("TargetNum"));
                if (detailJSON.getJSONObject(0).has("TodaySewNum")==true) txt_TodaySewNum.setText(detailJSON.getJSONObject(0).getString("TodaySewNum"));
                if (detailJSON.getJSONObject(0).has("ErrInfo")==true)
                {
                    MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(),R.raw.warn);
                    mediaPlayer.start();
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(getString(R.string.SystemHint)).setMessage(detailJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        System.out.println("fillFormtext----------edt_barcode置焦点");
        setEditBarcodeFocus();
    }
    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    {
        //设置焦点
        System.out.println("FragmentA 设置焦点-------------------------------1.Start");
        if (edt_barcode!=null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
            hideBottomUIMenu();
        }
        System.out.println("FragmentA 设置焦点-------------------------------1.End");
    }
    @Override
    public void onStart() {
        super.onStart();
        setEditBarcodeFocus();
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_find:
                if (edt_barcode.getText().length()==0) {
                    curToast.setText(getString(R.string.PleaseInputBarcode));
                    curToast.show();
                } else searchBarcodeData(edt_barcode.getText().toString(),txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString());
                break;
            case R.id.btn_Query:
                refreshDetailData("");
                setEditBarcodeFocus();
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;

            default:
                break;
        }
    }


    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    //刷新今日扫描明细;
    private void refreshDetailData(String paramDate)
    {
        try {
            detailJSON=new JSONArray("[]");
            //显示到orderListGrid中;
            final DetailListAdapter detailListAdapter=new DetailListAdapter(getActivity());
            detailListView.setAdapter(detailListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_AGetDetail @DepartmentNo='" + curDepartNo  + "',@WorkDate='"+paramDate
                + "',@OPERTYPE='DETAIL',@UserNo='"+curLoginUserNo+ "',@CPUID='" + CPUID +"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }





    private void ReadSQLData(String sql) {
        System.out.print("----存储过程:" + sql);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    /**
                     * [{"RoleName":"管理员"},{"RoleName":"调度"},{"RoleName":"装框操作"},{"RoleName":"物流运转"},{"RoleName":"试装箱"}]
                     */
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(sql);
                    if (jsonArray!=null&&jsonArray.length()>0){
                        String operType="";
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true) {
                            operType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        }
                        if (jsonArray.optJSONObject(0).has("OperType")==true) {
                            operType=jsonArray.optJSONObject(0).getString("OperType");
                        }
                        if (operType.toUpperCase().equals("SCANBARCODE"))
                        {
                            detailJSON=jsonArray;
                            Message msg = new Message();
                            msg.what = msgScanOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (operType.toUpperCase().equals("DETAIL"))
                        {
                            detailJSON=jsonArray;
                            Message msg = new Message();
                            msg.what = msgDetailOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle=new Bundle();
                            bundle.putString("HintInfo",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = msgError;
                            errmsg.setData(bundle);
                            fragmentHandler.removeMessages(errmsg.what);
                            fragmentHandler.sendMessage(errmsg);
                        }
                    } else {
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle=new Bundle();
                        bundle.putString("HintInfo","未返回任何数据!");
                        errmsg.what = msgError;
                        errmsg.setData(bundle);
                        fragmentHandler.removeMessages(errmsg.what);
                        fragmentHandler.sendMessage(errmsg);
                    };

                } catch (Exception e) {
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle=new Bundle();
                    bundle.putString("HintInfo",e.getMessage());
                    errmsg.what = msgError;
                    errmsg.setData(bundle);
                    fragmentHandler.removeMessages(errmsg.what);
                    fragmentHandler.sendMessage(errmsg);
                }
            }
        };
        new Thread(run).start();
    }

    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_a_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(38)));
            int color = getResources().getColor(R.color.black);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (detailJSON.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = detailJSON.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.txt_item_hoursection);// 显示文字
                if (detailJSON.optJSONObject(position).has("HourSection")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("HourSection").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_orderno);// 显示文字
                if (detailJSON.optJSONObject(position).has("OrderNo")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("OrderNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_styleno);// 显示文字
                if (detailJSON.optJSONObject(position).has("StyleNo")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("StyleNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_stylesort);// 显示文字
                if (detailJSON.optJSONObject(position).has("StyleSort")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("StyleSort").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_color);// 显示文字
                if (detailJSON.optJSONObject(position).has("Color")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Color").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_size);// 显示文字
                if (detailJSON.optJSONObject(position).has("Size")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Size").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_number);// 显示文字
                if (detailJSON.optJSONObject(position).has("Number")==true)
                    tv.setText(detailJSON.optJSONObject(position).get("Number").toString());
                tv.setTextColor(color);


            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }
    }

}
